<template>
  <div class="app-container">
    <div class="query-area">
      <a-row>
        <a-col :span="18">
          <a-form :model="queryParams" ref="queryRef" layout="inline" class="query-form">
            <a-form-item label="分类名称" field="classifyName">
              <a-input
                v-model="queryParams.classifyName"
                placeholder="请输入分类名称"
                allow-clear
                style="width: 200px"
                @keyup.enter="handleQuery" />
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" icon="Search" @click="handleQuery">搜索</a-button>
                <a-button @click="resetQuery">重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
        <right-toolbar v-model:showMoreSearch="showMoreSearch" @queryTable="getList"></right-toolbar>
      </a-row>
    </div>

    <div class="operation-area">
      <a-row class="operation-row">
        <a-space>
          <a-button type="primary" @click="handleAdd">添加分类</a-button>
        </a-space>
      </a-row>
    </div>

    <div class="table-area">
      <a-table
        class="custom-table"
        :loading="loading"
        :columns="columns"
        :data="comBusinessClassifyList"
        :row-selection="rowSelection"
        v-model:selected-keys="ids"
        row-key="classifyId"
        :pagination="{
          total: total,
          current: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          showJumper: true,
          showTotal: true,
          showPageSize: true,
          pageSizeOptions: [10, 20, 30, 50, 100, 200]
        }"
        @page-change="tablePageChange"
        @page-size-change="tablePageSizeChange">
        <template #createTime="{ record }">
          <span>{{ parseTime(record.createTime) }}</span>
        </template>
        <template #classifyStyle="{ record }">
          <dict-tag :options="function_classify_style" :value="record.classifyStyle" />
        </template>
        <template #optional="{ record }">
          <a-space>
            <a-button type="text" @click="handleUpdate(record)">编辑</a-button>
            <a-button type="text" status="danger" @click="handleDelete(record)">删除</a-button>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 添加或编辑业务管理-分类设置对话框 -->
    <a-modal
      :title="title"
      v-model:visible="open"
      unmount-on-close
      title-align="start"
      :mask-closable="false"
      width="600px">
      <a-form
        ref="comBusinessClassifyRef"
        :model="form"
        :rules="rules"
        auto-label-width
        label-width="80px"
        :disabled="isDisabled"
        style="--color-text-4: #444">
        <a-form-item label="分类名称" field="classifyName">
          <a-input :disabled="form.classifyId" v-model="form.classifyName" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item label="分类样式" field="classifyStyle">
          <a-select v-model="form.classifyStyle" placeholder="请选择分类样式" :disabled="form.classifyId">
            <a-option
              v-for="dict in function_classify_style"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排序" field="sort">
          <a-input-number v-model="form.sort" placeholder="请输入排序" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-row justify="end">
          <a-space>
            <a-button @click="cancel">{{ isDisabled ? '关闭' : '取消' }}</a-button>
            <a-button v-if="!isDisabled" type="primary" @click="submitForm" :loading="okLoading">确定</a-button>
          </a-space>
        </a-row>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="ComBusinessClassify">
import {
  listComBusinessClassify,
  getComBusinessClassify,
  delComBusinessClassify,
  addComBusinessClassify,
  updateComBusinessClassify,
  effectiveStatus
} from '@/api/common/comBusinessClassify'
import { Modal, Message } from '@arco-design/web-vue'
const router = useRouter()
const route = useRoute()
const functionCode = ref(route.params.functionCode)
const { proxy } = getCurrentInstance()
const { function_classify_style } = proxy.useDict('function_classify_style')
const comBusinessClassifyRef = ref(null)
const queryRef = ref(null)
const okLoading = ref(false)
const comBusinessClassifyList = ref([])
const open = ref(false)
const loading = ref(true)
const showMoreSearch = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const isDisabled = ref(false)
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: true
})
const columns = ref([
  {
    title: '序号',
    render: (data) => data.rowIndex + 1 // 添加序号
  },
  {
    title: '分类名称',
    dataIndex: 'classifyName'
  },
  {
    title: '分类样式',
    slotName: 'classifyStyle'
  },
  {
    title: '创建时间',
    slotName: 'createTime'
  },
  {
    title: '创建人',
    dataIndex: 'createName'
  },

  {
    title: '排序',
    dataIndex: 'sort'
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 200,
    align: 'center'
  }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    functionCode: functionCode.value,
    classifyName: null
  },
  rules: {
    classifyName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
    classifyStyle: [{ required: true, message: '分类样式不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 是否包含有效数据
const includeEffective = computed(() => {
  const selectedItems = comBusinessClassifyList.value.filter((item) => ids.value.includes(item.classifyId))
  return selectedItems.some((item) => parseInt(item.effectiveStatus) === 1)
})

watch(
  () => ids.value,
  () => {
    single.value = ids.value.length !== 1
    multiple.value = !ids.value.length
  }
)

/** 查询业务管理-分类设置列表 */
function getList() {
  loading.value = true
  listComBusinessClassify(queryParams.value).then((response) => {
    comBusinessClassifyList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    classifyId: null,
    functionCode: functionCode.value,
    classifyName: null,
    sort: null
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

// 分页变化
function tablePageChange(pageNum) {
  queryParams.value.pageNum = pageNum
  getList()
}

// 每页数据数量
function tablePageSizeChange(pageSize) {
  queryParams.value.pageSize = pageSize
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加分类'
}

/** 编辑按钮操作 */
function handleUpdate(row) {
  reset()
  const _classifyId = row.classifyId || ids.value
  getComBusinessClassify(_classifyId).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '编辑分类'
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.classifyId || ids.value
  Modal.warning({
    title: '确认删除',
    content: '是否确认删除所选数据？',
    hideCancel: false,
    bodyStyle: { 'text-align': 'center' },
    onOk: () => {
      delComBusinessClassify(_ids).then((res) => {
        getList()
        Message.success('删除成功')
      })
    }
  })
}

/** 提交按钮 */
function submitForm() {
  comBusinessClassifyRef.value.validate((valid) => {
    if (!valid) {
      okLoading.value = true
      if (form.value.classifyId != null) {
        updateComBusinessClassify(form.value)
          .then((response) => {
            Message.success('编辑成功')
            open.value = false
            getList()
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        addComBusinessClassify(form.value)
          .then((response) => {
            Message.success('新增成功')
            open.value = false
            getList()
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    } else {
      const keys = Object.keys(valid)
      comBusinessClassifyRef.value.scrollToField(keys[0])
    }
  })
}

getList()
</script>
